package com.likerSai;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 最长无重复子串
 *
 * @author sun.ye
 * @since 2021-04-26 11:34
 */
public class LengthOfLongestSubstring {

    public static void main(String[] args) {
        int maxStr = lengthOfLongestSubstringBatter("abba");
        System.out.println(maxStr);
    }


    public static int lengthOfLongestSubstring(String s) {
        if (s.length() == 0){
            return 0;
        }
        int strLength  = 0;
        Set<Character> strChar = new HashSet<>();
        for(int i = 0,j = 0 ; j < s.length() ; ){
            if(!strChar.contains(s.charAt(j))){
                strChar.add(s.charAt(j));
                j++;
            }else {
                strChar.remove(s.charAt(i));
                i++;
            }
            strLength = Math.max(strChar.size(), strLength);
        }
        return strLength;
    }

    public static int lengthOfLongestSubstringBatter(String s) {
        if (s.length() == 0){
            return 0;
        }
        int strLength  = 0;

        Map<Character, Integer> dictionary = new HashMap<>();
        int start = 0;
        for( int end = 0 ; end < s.length() ; end++ ){
            char endChar = s.charAt(end);
            if (dictionary.containsKey(endChar)){
                start = Math.max(dictionary.get(endChar) + 1,start);
                dictionary.put(endChar,end);
            }else {
                dictionary.put(s.charAt(end),end);
            }

            strLength = Math.max(end - start + 1,strLength);
        }
        return strLength;
    }

}